// event stream

const clientId = 'user-' + Math.random().toString(36).substr(2, 9);
let eventSource = null;

function connect() {
    // 断开现有连接
    if (eventSource) {
        eventSource.close();
    }

    // 创建新的SSE连接
    eventSource = new EventSource(`/api/events/stream?clientId=${clientId}`);
    // 显示在页面中
    document.getElementById('clientIdDisplay').textContent = `${clientId}`;

    eventSource.onopen = function(event) {
        addMessage('连接已建立');
    };

    eventSource.onmessage = function(event) {
        const data = JSON.parse(event.data);
        addMessage(`消息: ${JSON.stringify(data)}`);
    };

    eventSource.addEventListener('custom-message', function(event) {
        const data = JSON.parse(event.data);
        addMessage(`自定义消息: ${JSON.stringify(data)}`);
    });

    eventSource.addEventListener('broadcast', function(event) {
        const data = JSON.parse(event.data);
        addMessage(`广播: ${JSON.stringify(data)}`);
    });

    eventSource.onerror = function(event) {
        addMessage('连接错误，尝试重连...');
    };
}

function addMessage(message) {
    const div = document.createElement('div');
    div.textContent = new Date().toLocaleTimeString() + ' - ' + message;
    document.getElementById('messages').appendChild(div);
}


// postMessage receiver ----------------------------------------------------------------------------------------------

// 显示消息的函数
function displayMessage(message, source) {
    const log = document.getElementById('messageLog');
    const messageItem = document.createElement('div');
    messageItem.className = 'message-item';
    messageItem.innerHTML = `
                <strong>${source}:</strong> ${JSON.stringify(message)}<br>
                <small>时间: ${new Date().toLocaleString()}</small>
            `;
    log.appendChild(messageItem);
    log.scrollTop = log.scrollHeight;
}

// 回复父窗口 (适用于 iframe)
function replyToParent() {
    if (window.parent !== window) {
        const replyMessage = document.getElementById('replyInput').value;
        window.parent.postMessage({
            type: 'reply-from-iframe',
            message: replyMessage,
            replyTo: 'iframe-parent'
        }, '*'); // 在实际应用中应该指定具体的域名
    } else {
        alert('当前不在 iframe 中，无法回复父窗口');
    }
}

// 回复 opener 窗口 (适用于弹窗)
function replyToOpener() {
    if (window.opener) {
        const replyMessage = document.getElementById('replyInput').value;
        window.opener.postMessage({
            type: 'reply-from-popup',
            message: replyMessage,
            replyTo: 'popup-parent'
        }, '*'); // 在实际应用中应该指定具体的域名
    } else {
        alert('没有 opener 窗口，无法回复');
    }
}



// send ----------------------------------------------------------------------------------------------
let receiverWindow = null;

// 发送消息到 iframe
function sendMessageToIframe() {
    const message = document.getElementById('messageInput').value;
    const iframe = document.getElementById('receiverFrame');

    // 向 iframe 发送消息
    iframe.contentWindow.postMessage({
        type: 'from-iframe-parent',
        message: message,
        timestamp: new Date().toISOString()
    }, '*'); // 在实际应用中应该指定具体的域名

    console.log('消息已发送到 iframe:', message);
}

// 打开接收窗口
function openReceiverWindow() {
    receiverWindow = window.open('/receiver', 'receiverWindow', 'width=600,height=400');
    if (!receiverWindow) {
        alert('弹窗被阻止，请允许弹窗后重试');
    }
}

// 发送消息到弹出窗口
function sendMessageToPopup() {
    if (!receiverWindow || receiverWindow.closed) {
        alert('请先打开接收窗口');
        return;
    }

    const message = document.getElementById('popupMessageInput').value;
    receiverWindow.postMessage({
        type: 'from-popup-parent',
        message: message,
        timestamp: new Date().toISOString()
    }, '*'); // 在实际应用中应该指定具体的域名

    console.log('消息已发送到弹出窗口:', message);
}

// 监听来自 iframe 的消息
window.addEventListener('message', function(event) {
    // 在实际应用中应该验证 event.origin
    console.log('来自 iframe 的消息:', event.data);

    // 显示接收到的消息
    const messageDiv = document.createElement('div');
    messageDiv.textContent = `收到来自 iframe 的回复: ${JSON.stringify(event.data)}`;
    messageDiv.style.color = 'blue';
    document.body.appendChild(messageDiv);
});



